package day0303;

import org.w3c.dom.Node;

/**
 * 单链表:
 *  1. 添加元素
 *  2. 删除元素
 *  3. 查找元素
 *  4. 大小
 */
public class MyLink {

    private Node head;

    private int size;

    public void add(Object element){
        if (null == element) {
            throw new NullPointerException("现在不能存 null");
        }
        Node curr = new Node(element, null);
        if (head == null) {
            head = curr;
        } else {
            Node node = head;
            // 遍历找到最后的元素
            while(node.next != null){
                node = node.next;
            }
            node.next = curr;
        }
        size ++;
    }

    public Object remove(int index) {
        // TODO(下标是否合法)
        Node obj = null;
        if (index == 0){
            obj = head;
            head = head.next;
        } else {
            // 被删元素的前一个元素
            Node pre = head;
            // 被删除的元素
            Node node = head.next;
            for (int i = 1; i < index; i++) {
                pre = node;
                node = node.next;
            }
            obj = node;

            pre.next = node.next;

        }
        size --;
        return obj.value;
    }

    public Object remove(Object element) {
        // 被删除的元素
        Node node = null;
        if (head.value.equals(element)) {
            node = head;
            head = head.next; // 删除
            size --;
            return node.value;
        }else {
            Node pre = head;
            node = head.next;
            while (node != null) {
                if(node.value.equals(element)) {
                    // 相等
                    pre.next = node.next;
                    size --;
                    return node.value;
                } else{
                    pre = node;
                    node = node.next;
                }
            }
        }
        return null;
    }

    public Object get(int index){
        // TODO(index 合法性)
        if (index == 0) {
            return head.value;
        } else {
            Node node = head.next;
            for (int i = 1; i < index; i++) {
                node = node.next;
            }
            return node.value;
        }

    }

    public int size(){
        return this.size;
    }

    public String toString(){
        StringBuilder sb = new StringBuilder("MyLink[");
        Node node = head;

        while (node != null) {
            sb.append(node.value + ", ");
            node = node.next;
        }
        return sb.substring(0, sb.length() - 2) + "]";
    }


    private class Node {
        private Object value;

        private Node next;

        public Node(Object value, Node next) {
            this.value = value;
            this.next = next;
        }
    }
}
